<script setup lang="ts">
import { getEmailVerificationCode, getRegisterWithEmail } from '@/common/service/user-service'
import type { EmailRegistration } from '@/common/types/user-type'
import { message } from 'ant-design-vue'
import type { UnwrapRef } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/common/stores/modules/users-store'

const { countdown, isCounting, startCountdown, resetCountdown } =
  useCountdown(60)

const formRef = ref()
const labelCol = { span: 24 }
const wrapperCol = { span: 24 }
const labelCol1 = { span: 8 }
const wrapperCol1 = { span: 16 }
const router = useRouter()
const userStore = useUserStore()

// 获取注册邮箱验证码
const emailPattern = async () => {
  try {
    // 调用接口，传递邮箱地址
    await getEmailVerificationCode(formState.email)
    message.success('验证码已发送！')
    startCountdown()
  } catch (error) {
    message.error('获取验证码失败，请稍后重试')
    console.error('接口调用错误:', error)
  }
}

// 使用 defineEmits 定义事件
const emit = defineEmits<{
  (event: 'registerClicked', value: boolean): void
}>()

// 点击 "注册账号" 时，触发父组件的事件
const onregister = () => {
  emit('registerClicked', true)
}

// 初始数据
const formState: UnwrapRef<EmailRegistration> = reactive({
  email: '', // 邮箱账号
  password: '', // 密码
  repassword: '', //  两次验证的密码
  code: '', // 验证码
  remember: [], // 用户协议
})
// 校验规则
const rules = reactive(getRules(formState))

// 点击登录
const onSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()

    // 调用注册接口，进行验证码校验
    const response = await getRegisterWithEmail(formState.email, formState.code)

    const token = response.data._rawValue.data
    console.log(token, 'Authorization')

    console.log(response.data, '数据')

    // 访问返回的实际数据
    const responseData = response.data // 获取 data 字段中的实际数据

    // 检查后端返回的数据结构和验证码是否有效
    if (responseData._rawValue.code !== 0) {
      message.error('验证码不正确')
      return // 验证码不正确时，停止后续逻辑
    }

    // 验证码正确，继续执行注册逻辑
    const userData = {
      user: formState.email,
      password: formState.password,
      token,
    }

    userStore.setUserInfo(userData)
    message.success('注册成功')

    // 跳转到首页
    router.push('/')
  } catch (error) {
    // 捕获异常并提供用户友好的错误信息
    console.error('注册失败:', error)
    message.error('注册失败，请重试')
  }
}
</script>

<template>
  <!-- 邮箱登录 -->
  <a-form
    class="login-name"
    :label-col="labelCol1"
    :wrapper-col="wrapperCol1"
    ref="formRef"
    :model="formState"
    :rules="rules"
  >
    <a-form-item
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      label="邮箱"
      ref="email"
      name="email"
    >
      <a-input
        class="login-name-input"
        placeholder="请输入邮箱如vip@qq.com"
        v-model:value="formState.email"
      />
    </a-form-item>

    <!-- 密码 -->
    <!-- 验证码 -->
    <a-form-item
      label="验证"
      ref="code"
      name="code"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-input-search v-model:value="formState.code" placeholder="验证码">
        <template #enterButton>
          <a-button @click="emailPattern">
            {{ isCounting ? `${countdown}秒后重试` : '获取验证码' }}</a-button
          >
        </template>
      </a-input-search>
    </a-form-item>

    <!-- 隐私协议 -->
    <a-form-item
      class="login-name-agreement"
      ref="remember"
      name="remember"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-checkbox-group v-model:value="formState.remember">
        <a-checkbox class="login-name-agreement-text">
          勾选即代表你同意并接受
          <span class="login-name-agreement-text-span"
            >服务协议·隐私政策《SparkDesk隐私政策》·《SparkDesk用户协议》</span
          >
        </a-checkbox>
      </a-checkbox-group>
    </a-form-item>

    <!-- 登录 -->
    <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-button class="login-name-button" type="primary" @click="onSubmit"
        >登录</a-button
      >
    </a-form-item>

    <!-- 注册 -->
    <a-form-item class="login-name-register" @click="onregister"
      >注册账号</a-form-item
    >
  </a-form>
</template>

<style lang="scss" scoped>
.login-name-agreement-text {
  font-size: 12px;
  color: $educ-color-white;

  &-span {
    color: #14f417;
  }
}

.login-name-button {
  width: 100%;
}

.login-name-register {
  color: $educ-color-white;
  cursor: pointer;
}

// 输入框内边距
:deep .ant-input,
.ant-input-affix-wrapper {
  padding: 6px;
}
</style>
